<?php
/**
 * Created by PhpStorm.
 * User: Kofi
 * Date: 2018-03-07
 * Time: 23:47.
 */

namespace App\Libraries\Listeners;

use DateTime;
use Illuminate\Database\Events\QueryExecuted;
use DB;
use Log;

class QueryListener
{
    /**
     * Create the event listener.
     */
    public function __construct()
    {
    }

    /**
     * Handle the event.
     *
     * @param QueryExecuted $event
     *
     * @return void
     */
    public function handle(QueryExecuted $event)
    {
        $time = $event->time;
        $bindings = $event->bindings;
        foreach ($bindings as $i => $binding) {
            if ($binding instanceof DateTime) {
                $bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
            } elseif (is_string($binding)) {
                $bindings[$i] = DB::getPdo()->quote($binding);
            } elseif (null === $binding) {
                $bindings[$i] = 'null';
            }
        }
        $query = str_replace(array('%', '?', "\r", "\n", "\t"), array('%%', '%s', ' ', ' ', ' '), $event->sql);
        $query = preg_replace('/\s+/uD', ' ', $query);
        $query = vsprintf($query, $bindings).';';
        Log::debug($query.'{ 耗时: '.$time.'毫秒 }');
    }
}
